import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TextInput,
  TouchableOpacity,
  Alert,
  SafeAreaView,
} from 'react-native';
import { Picker } from '@react-native-picker/picker';
import { VehicleFormData, MediaFile } from '../../types';
import MediaUploader from '../../components/MediaUploader';
import AIScoringCard from '../../components/AIScoringCard';
import { AIScoreResult } from '../../services/aiScoring';
import axios from 'axios';

const AddScreen = () => {
  const [formData, setFormData] = useState<VehicleFormData>({
    title: '',
    brand: '',
    model: '',
    year: '',
    mileage: '',
    price: '',
    condition: '',
    fuelType: '',
    transmission: '',
    bodyType: '',
    color: '',
    province: '河北',
    description: '',
    engineSize: '',
    power: '',
    features: [],
    city: '保定',
    address: '',
    batteryHealth: '',
    chargingType: '',
    warrantyInfo: '',
  });

  const [mediaFiles, setMediaFiles] = useState<MediaFile[]>([]);
  const [currentStep, setCurrentStep] = useState(1);
  const [selectedFeatures, setSelectedFeatures] = useState<string[]>([]);
  const [aiScoreResult, setAiScoreResult] = useState<AIScoreResult | null>(null);

  // 新能源二手车专用选项数据
  const conditions = [
    { label: '准新车', value: 'excellent' },
    { label: '良好', value: 'good' },
    { label: '一般', value: 'fair' },
    { label: '需要维修', value: 'poor' },
  ];

  const fuelTypes = [
    { label: '纯电动', value: 'electric' },
    { label: '插电混动', value: 'plug-in-hybrid' },
    { label: '油电混动', value: 'hybrid' },
    { label: '增程式', value: 'range-extender' },
  ];

  const transmissions = [
    { label: '单速变速箱', value: 'single-speed' },
    { label: '多速变速箱', value: 'multi-speed' },
    { label: '无变速箱', value: 'no-transmission' },
  ];

  const bodyTypes = [
    { label: '轿车', value: 'sedan' },
    { label: 'SUV', value: 'suv' },
    { label: '掀背车', value: 'hatchback' },
    { label: '旅行车', value: 'wagon' },
    { label: 'MPV', value: 'mpv' },
    { label: '跑车', value: 'coupe' },
    { label: '微型车', value: 'micro' },
  ];

  // 保定市区域
  const baodingDistricts = [
    '竞秀区', '莲池区', '满城区', '清苑区', '徐水区', '涞水县', '阜平县', 
    '定兴县', '唐县', '高阳县', '容城县', '涞源县', '望都县', '安新县', 
    '易县', '曲阳县', '蠡县', '顺平县', '博野县', '雄县', '涿州市', '定州市', '安国市', '高碑店市'
  ];

  // 新能源车专用配置
  const features = [
    '快充接口', '慢充接口', '无线充电', '智能驾驶', '自动泊车', '车道保持',
    '自适应巡航', '全景天窗', '真皮座椅', '座椅加热', '座椅通风', '方向盘加热',
    '大屏导航', '语音控制', '远程控制', 'OTA升级', '能量回收', '运动模式',
    '经济模式', '雪地模式', '360度影像', '自动空调', '空气净化', '氛围灯'
  ];

  // 新能源车品牌
  const newEnergyBrands = [
    '比亚迪', '特斯拉', '蔚来', '小鹏', '理想', '广汽埃安', '北汽新能源',
    '吉利几何', '奇瑞新能源', '长安新能源', '上汽荣威', '东风岚图', '长城欧拉',
    '零跑', '哪吒', '威马', '天际', '爱驰', '合众', '华人运通'
  ];

  const handleInputChange = (field: keyof VehicleFormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleFeatureToggle = (feature: string) => {
    setSelectedFeatures(prev => 
      prev.includes(feature) 
        ? prev.filter(f => f !== feature)
        : [...prev, feature]
    );
  };

  const handleMediaChange = (files: MediaFile[]) => {
    setMediaFiles(files);
  };

  const handleSubmit = async () => {
    try {
      console.log('🚀 开始提交车辆信息:', formData);
      console.log('📸 媒体文件:', mediaFiles);
      console.log('🤖 AI评分:', aiScoreResult);
      
      const response = await axios.post('http://192.168.192.147:3000/sow/vehicle', {
        ...formData,
        features: selectedFeatures,
        mediaFiles: mediaFiles.map(file => file.uri),
        aiScore: aiScoreResult?.score || null,
        aiReasoning: aiScoreResult?.reasoning || null,
      });
      
      console.log('✅ 车辆信息提交成功:', response.data);
      
      Alert.alert('成功', '新能源二手车信息添加成功！');
      // 重置表单
      setFormData({
        title: '',
        brand: '',
        model: '',
        year: '',
        mileage: '',
        price: '',
        condition: '',
        fuelType: '',
        transmission: '',
        bodyType: '',
        color: '',
        province: '河北',
        description: '',
        engineSize: '',
        power: '',
        features: [],
        city: '保定',
        address: '',
        batteryHealth: '',
        chargingType: '',
        warrantyInfo: '',
      });
      setMediaFiles([]);
      setCurrentStep(1);
      setSelectedFeatures([]);
      setAiScoreResult(null);
    } catch (error: any) {
      console.error('❌ 车辆信息提交失败:', error);
      console.error('❌ 错误详情:', error.response?.data);
      console.error('❌ 状态码:', error.response?.status);
      
      let errorMessage = '添加失败';
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      Alert.alert('错误', errorMessage);
    }
  };

  const handleAIScoreComplete = (result: AIScoreResult) => {
    setAiScoreResult(result);
    Alert.alert('AI评分完成', `您的新能源二手车评分为 ${result.score.toFixed(1)} 分`);
  };

  const renderStep1 = () => (
    <View style={styles.stepContainer}>
      <Text style={styles.stepTitle}>基本信息</Text>
      
      <View style={styles.inputGroup}>
        <Text style={styles.label}>车辆标题 *</Text>
        <TextInput
          style={styles.input}
          value={formData.title}
          onChangeText={(value) => handleInputChange('title', value)}
          placeholder="请输入新能源二手车标题"
        />
      </View>

      <View style={styles.row}>
        <View style={[styles.inputGroup, { flex: 1, marginRight: 10 }]}>
          <Text style={styles.label}>品牌 *</Text>
          <View style={styles.pickerContainer}>
            <Picker
              selectedValue={formData.brand}
              onValueChange={(value: string) => handleInputChange('brand', value)}
              style={styles.picker}
            >
              <Picker.Item label="请选择品牌" value="" />
              {newEnergyBrands.map(brand => (
                <Picker.Item key={brand} label={brand} value={brand} />
              ))}
            </Picker>
          </View>
        </View>
        <View style={[styles.inputGroup, { flex: 1 }]}>
          <Text style={styles.label}>型号</Text>
          <TextInput
            style={styles.input}
            value={formData.model}
            onChangeText={(value) => handleInputChange('model', value)}
            placeholder="如：秦PLUS"
          />
        </View>
      </View>

      <View style={styles.row}>
        <View style={[styles.inputGroup, { flex: 1, marginRight: 10 }]}>
          <Text style={styles.label}>年份</Text>
          <TextInput
            style={styles.input}
            value={formData.year}
            onChangeText={(value) => handleInputChange('year', value)}
            placeholder="如：2022"
            keyboardType="numeric"
          />
        </View>
        <View style={[styles.inputGroup, { flex: 1 }]}>
          <Text style={styles.label}>里程(万公里)</Text>
          <TextInput
            style={styles.input}
            value={formData.mileage}
            onChangeText={(value) => handleInputChange('mileage', value)}
            placeholder="如：2.5"
            keyboardType="numeric"
          />
        </View>
      </View>

      <View style={styles.inputGroup}>
        <Text style={styles.label}>价格(万元) *</Text>
        <TextInput
          style={styles.input}
          value={formData.price}
          onChangeText={(value) => handleInputChange('price', value)}
          placeholder="如：18.8"
          keyboardType="numeric"
        />
      </View>
    </View>
  );

  const renderStep2 = () => (
    <View style={styles.stepContainer}>
      <Text style={styles.stepTitle}>新能源车详情</Text>
      
      <View style={styles.row}>
        <View style={[styles.inputGroup, { flex: 1, marginRight: 10 }]}>
          <Text style={styles.label}>车况</Text>
          <View style={styles.pickerContainer}>
            <Picker
              selectedValue={formData.condition}
              onValueChange={(value: string) => handleInputChange('condition', value)}
              style={styles.picker}
            >
              <Picker.Item label="请选择车况" value="" />
              {conditions.map(item => (
                <Picker.Item key={item.value} label={item.label} value={item.value} />
              ))}
            </Picker>
          </View>
        </View>
        <View style={[styles.inputGroup, { flex: 1 }]}>
          <Text style={styles.label}>动力类型</Text>
          <View style={styles.pickerContainer}>
            <Picker
              selectedValue={formData.fuelType}
              onValueChange={(value: string) => handleInputChange('fuelType', value)}
              style={styles.picker}
            >
              <Picker.Item label="请选择动力类型" value="" />
              {fuelTypes.map(item => (
                <Picker.Item key={item.value} label={item.label} value={item.value} />
              ))}
            </Picker>
          </View>
        </View>
      </View>

      <View style={styles.row}>
        <View style={[styles.inputGroup, { flex: 1, marginRight: 10 }]}>
          <Text style={styles.label}>变速箱</Text>
          <View style={styles.pickerContainer}>
            <Picker
              selectedValue={formData.transmission}
              onValueChange={(value: string) => handleInputChange('transmission', value)}
              style={styles.picker}
            >
              <Picker.Item label="请选择变速箱" value="" />
              {transmissions.map(item => (
                <Picker.Item key={item.value} label={item.label} value={item.value} />
              ))}
            </Picker>
          </View>
        </View>
        <View style={[styles.inputGroup, { flex: 1 }]}>
          <Text style={styles.label}>车身类型</Text>
          <View style={styles.pickerContainer}>
            <Picker
              selectedValue={formData.bodyType}
              onValueChange={(value: string) => handleInputChange('bodyType', value)}
              style={styles.picker}
            >
              <Picker.Item label="请选择车身类型" value="" />
              {bodyTypes.map(item => (
                <Picker.Item key={item.value} label={item.label} value={item.value} />
              ))}
            </Picker>
          </View>
        </View>
      </View>

      <View style={styles.row}>
        <View style={[styles.inputGroup, { flex: 1, marginRight: 10 }]}>
          <Text style={styles.label}>颜色</Text>
          <TextInput
            style={styles.input}
            value={formData.color}
            onChangeText={(value) => handleInputChange('color', value)}
            placeholder="如：珍珠白"
          />
        </View>
        <View style={[styles.inputGroup, { flex: 1 }]}>
          <Text style={styles.label}>电池容量</Text>
          <TextInput
            style={styles.input}
            value={formData.engineSize}
            onChangeText={(value) => handleInputChange('engineSize', value)}
            placeholder="如：60kWh"
          />
        </View>
      </View>

      <View style={styles.row}>
        <View style={[styles.inputGroup, { flex: 1, marginRight: 10 }]}>
          <Text style={styles.label}>续航里程</Text>
          <TextInput
            style={styles.input}
            value={formData.power}
            onChangeText={(value) => handleInputChange('power', value)}
            placeholder="如：500公里"
          />
        </View>
        <View style={[styles.inputGroup, { flex: 1 }]}>
          <Text style={styles.label}>电池健康度</Text>
          <TextInput
            style={styles.input}
            value={formData.batteryHealth || ''}
            onChangeText={(value) => handleInputChange('batteryHealth', value)}
            placeholder="如：95%"
          />
        </View>
      </View>

      <View style={styles.inputGroup}>
        <Text style={styles.label}>充电类型</Text>
        <TextInput
          style={styles.input}
          value={formData.chargingType || ''}
          onChangeText={(value) => handleInputChange('chargingType', value)}
          placeholder="如：快充/慢充/无线充电"
        />
      </View>
    </View>
  );

  const renderStep3 = () => (
    <View style={styles.stepContainer}>
      <Text style={styles.stepTitle}>配置与位置</Text>
      
      <View style={styles.inputGroup}>
        <Text style={styles.label}>新能源车配置</Text>
        <View style={styles.featuresContainer}>
          {features.map(feature => (
            <TouchableOpacity
              key={feature}
              style={[
                styles.featureTag,
                selectedFeatures.includes(feature) && styles.featureTagSelected
              ]}
              onPress={() => handleFeatureToggle(feature)}
            >
              <Text style={[
                styles.featureText,
                selectedFeatures.includes(feature) && styles.featureTextSelected
              ]}>
                {feature}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
      </View>

      <View style={styles.row}>
        <View style={[styles.inputGroup, { flex: 1, marginRight: 10 }]}>
          <Text style={styles.label}>保定市区域</Text>
          <View style={styles.pickerContainer}>
            <Picker
              selectedValue={formData.address}
              onValueChange={(value: string) => handleInputChange('address', value)}
              style={styles.picker}
            >
              <Picker.Item label="请选择区域" value="" />
              {baodingDistricts.map(district => (
                <Picker.Item key={district} label={district} value={district} />
              ))}
            </Picker>
          </View>
        </View>
        <View style={[styles.inputGroup, { flex: 1 }]}>
          <Text style={styles.label}>详细地址</Text>
          <TextInput
            style={styles.input}
            value={formData.address}
            onChangeText={(value) => handleInputChange('address', value)}
            placeholder="请输入详细地址"
          />
        </View>
      </View>

      <View style={styles.inputGroup}>
        <Text style={styles.label}>保修信息</Text>
        <TextInput
          style={styles.input}
          value={formData.warrantyInfo || ''}
          onChangeText={(value) => handleInputChange('warrantyInfo', value)}
          placeholder="如：电池8年质保，整车3年质保"
        />
      </View>
    </View>
  );

  const renderStep4 = () => (
    <View style={styles.stepContainer}>
      <Text style={styles.stepTitle}>AI智能评分</Text>
      <Text style={styles.stepSubtitle}>基于新能源二手车信息的专业评估</Text>
      
      <AIScoringCard
        vehicleData={formData}
        onScoreComplete={handleAIScoreComplete}
      />
    </View>
  );

  const renderStep5 = () => (
    <View style={styles.stepContainer}>
      <Text style={styles.stepTitle}>媒体与描述</Text>
      
      <View style={styles.inputGroup}>
        <Text style={styles.label}>车辆描述</Text>
        <TextInput
          style={[styles.input, styles.textArea]}
          value={formData.description}
          onChangeText={(value) => handleInputChange('description', value)}
          placeholder="请详细描述新能源二手车状况、电池健康度、充电情况、历史、优势等信息..."
          multiline
          numberOfLines={4}
          textAlignVertical="top"
        />
      </View>

      <View style={styles.inputGroup}>
        <Text style={styles.label}>添加图片/视频</Text>
        <MediaUploader
          mediaFiles={mediaFiles}
          onMediaChange={handleMediaChange}
          maxFiles={10}
        />
      </View>
    </View>
  );

  const renderStepIndicator = () => (
    <View style={styles.stepIndicator}>
      {[1, 2, 3, 4, 5].map(step => (
        <View key={step} style={styles.stepDotContainer}>
          <View style={[
            styles.stepDot,
            currentStep >= step && styles.stepDotActive
          ]} />
          <Text style={[
            styles.stepDotText,
            currentStep >= step && styles.stepDotTextActive
          ]}>
            {step}
          </Text>
        </View>
      ))}
    </View>
  );

  const nextStep = () => {
    if (currentStep < 5) {
      setCurrentStep(currentStep + 1);
    }
  };

  const prevStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerTitle}>添加新能源二手车</Text>
        <Text style={styles.headerSubtitle}>保定市内新能源二手车信息发布</Text>
      </View>

      {renderStepIndicator()}

      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        {currentStep === 1 && renderStep1()}
        {currentStep === 2 && renderStep2()}
        {currentStep === 3 && renderStep3()}
        {currentStep === 4 && renderStep4()}
        {currentStep === 5 && renderStep5()}
      </ScrollView>

      <View style={styles.footer}>
        {currentStep > 1 && (
          <TouchableOpacity style={styles.prevButton} onPress={prevStep}>
            <Text style={styles.prevButtonText}>上一步</Text>
          </TouchableOpacity>
        )}
        
        {currentStep < 5 ? (
          <TouchableOpacity style={styles.nextButton} onPress={nextStep}>
            <Text style={styles.nextButtonText}>下一步</Text>
          </TouchableOpacity>
        ) : (
          <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
            <Text style={styles.submitButtonText}>提交</Text>
          </TouchableOpacity>
        )}
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F8F9FA',
  },
  header: {
    padding: 20,
    backgroundColor: '#FFFFFF',
    borderBottomWidth: 1,
    borderBottomColor: '#E5E5E5',
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 5,
  },
  headerSubtitle: {
    fontSize: 16,
    color: '#666',
  },
  stepIndicator: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#FFFFFF',
    borderBottomWidth: 1,
    borderBottomColor: '#E5E5E5',
  },
  stepDotContainer: {
    alignItems: 'center',
    marginHorizontal: 15,
  },
  stepDot: {
    width: 30,
    height: 30,
    borderRadius: 15,
    backgroundColor: '#E5E5E5',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 5,
  },
  stepDotActive: {
    backgroundColor: '#007AFF',
  },
  stepDotText: {
    fontSize: 14,
    color: '#999',
    fontWeight: '600',
  },
  stepDotTextActive: {
    color: '#FFFFFF',
  },
  content: {
    flex: 1,
    padding: 20,
  },
  stepContainer: {
    backgroundColor: '#FFFFFF',
    borderRadius: 12,
    padding: 20,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  stepTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 20,
    textAlign: 'center',
  },
  inputGroup: {
    marginBottom: 20,
  },
  label: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 8,
  },
  input: {
    borderWidth: 1,
    borderColor: '#E5E5E5',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    backgroundColor: '#FFFFFF',
  },
  textArea: {
    height: 100,
    textAlignVertical: 'top',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  pickerContainer: {
    borderWidth: 1,
    borderColor: '#E5E5E5',
    borderRadius: 8,
    backgroundColor: '#FFFFFF',
  },
  picker: {
    height: 50,
  },
  featuresContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 10,
  },
  featureTag: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: '#F0F0F0',
    marginRight: 10,
    marginBottom: 10,
    borderWidth: 1,
    borderColor: '#E5E5E5',
  },
  featureTagSelected: {
    backgroundColor: '#007AFF',
    borderColor: '#007AFF',
  },
  featureText: {
    fontSize: 14,
    color: '#666',
  },
  featureTextSelected: {
    color: '#FFFFFF',
  },
  addMediaButton: {
    backgroundColor: '#007AFF',
    paddingVertical: 15,
    paddingHorizontal: 20,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 10,
  },
  addMediaButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '600',
  },
  mediaPreview: {
    marginTop: 15,
    padding: 15,
    backgroundColor: '#F8F9FA',
    borderRadius: 8,
    alignItems: 'center',
  },
  mediaCount: {
    fontSize: 14,
    color: '#666',
  },
  footer: {
    flexDirection: 'row',
    padding: 20,
    backgroundColor: '#FFFFFF',
    borderTopWidth: 1,
    borderTopColor: '#E5E5E5',
  },
  prevButton: {
    flex: 1,
    paddingVertical: 15,
    paddingHorizontal: 20,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#E5E5E5',
    marginRight: 10,
    alignItems: 'center',
  },
  prevButtonText: {
    fontSize: 16,
    color: '#666',
    fontWeight: '600',
  },
  nextButton: {
    flex: 1,
    paddingVertical: 15,
    paddingHorizontal: 20,
    borderRadius: 8,
    backgroundColor: '#007AFF',
    alignItems: 'center',
  },
  nextButtonText: {
    fontSize: 16,
    color: '#FFFFFF',
    fontWeight: '600',
  },
  submitButton: {
    flex: 1,
    paddingVertical: 15,
    paddingHorizontal: 20,
    borderRadius: 8,
    backgroundColor: '#28A745',
    alignItems: 'center',
  },
  submitButtonText: {
    fontSize: 16,
    color: '#FFFFFF',
    fontWeight: '600',
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 20,
  },
  stepSubtitle: {
    fontSize: 14,
    color: '#666',
    marginBottom: 20,
    textAlign: 'center',
  },
});

export default AddScreen; 